///**************************************************************************************
// *
// * @(#) TemplateService.java
// * @Package com.jgdt.jgdtkasannong_university_gene_backend.service.test
// **************************************************************************************/
//package com.jgdt.jgdtkasannong_university_gene_backend.service.test.impl;
//
//import cn.hutool.core.io.resource.InputStreamResource;
//import cn.hutool.core.io.resource.Resource;
//import com.jgdt.jgdtkasannong_university_gene_backend.entity.test.*;
//import com.jgdt.jgdtkasannong_university_gene_backend.mapper.test.TemplateMapper;
//import com.jgdt.jgdtkasannong_university_gene_backend.service.test.TemplateService;
//import com.jgdt.jgdtkasannong_university_gene_backend.utils.excel.ExcelImageUtils;
//import jakarta.servlet.http.HttpServletResponse;
//import org.apache.commons.compress.utils.IOUtils;
//import org.apache.poi.poifs.filesystem.POIFSFileSystem;
//import org.apache.poi.ss.usermodel.*;
//import org.apache.poi.xssf.usermodel.XSSFRow;
//import org.apache.poi.xssf.usermodel.XSSFSheet;
//import org.apache.poi.xssf.usermodel.XSSFWorkbook;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.core.io.FileSystemResource;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.MediaType;
//import org.springframework.http.ResponseEntity;
//import org.springframework.scheduling.annotation.Async;
//import org.springframework.stereotype.Service;
//import org.springframework.web.context.request.async.DeferredResult;
//import org.springframework.web.multipart.MultipartFile;
//
//import javax.imageio.ImageIO;
//import java.awt.image.BufferedImage;
//import java.io.ByteArrayInputStream;
//import java.io.ByteArrayOutputStream;
//import java.io.IOException;
//import java.io.InputStream;
//import java.nio.file.Files;
//import java.nio.file.Path;
//import java.nio.file.Paths;
//import java.util.*;
//
//@Service
//public class TemplateServiceImpl implements TemplateService {
//
//
//    @Autowired
//    private TemplateMapper templateMapper;
//
//    @Value("${file.upload-dir}")
//    private String uploadDir;
//
//
////    @Override
////    public void downloadTemplate(HttpServletResponse response) {
////        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
////        response.setHeader("Content-Disposition", "attachment; filename=template.xlsx");
////        try {
////            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
////            // Sheet1数据
////            WriteSheet sheet1 = EasyExcel.writerSheet(0, "Sheet1")
////                    .head(Sheet1Data.class)
////                    .build();
////            excelWriter.write(querySheet1Data(), sheet1);
////
////            // Sheet2数据
////            WriteSheet sheet2 = EasyExcel.writerSheet(1, "Sheet2")
////                    .head(Sheet2Data.class)
////                    .build();
////            excelWriter.write(querySheet2Data(), sheet2);
////            excelWriter.finish();
////        } catch (IOException e) {
////            throw new RuntimeException(e);
////        }
////    }
//
//    @Override
//    public void downloadTemplate(HttpServletResponse response) {
//        try {
//            // 1. 创建工作簿和工作表
//            XSSFWorkbook workbook = new XSSFWorkbook();
//            XSSFSheet sheet = workbook.createSheet("数据报表");
//
//            // 2. 填充数据（示例）
//            XSSFRow headerRow = sheet.createRow(0);
//            headerRow.createCell(0).setCellValue("ID");
//            headerRow.createCell(1).setCellValue("名称");
//            XSSFRow dataRow = sheet.createRow(1);
//            dataRow.createCell(0).setCellValue(1);
//            dataRow.createCell(1).setCellValue("测试数据");
//
//
////            // 3. 加载图片文件
////            // 对于实际应用，你可能需要从文件系统绝对路径加载
////            FileSystemResource imgFile = new FileSystemResource("D:/00d9a7a1-bb7a-43dd-b37c-e0d3bad0b746.jpg");
////            InputStream inputStream = imgFile.getInputStream();
////            byte[] bytes = IOUtils.toByteArray(inputStream);
////            int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
////            inputStream.close();
////
////
////            // 4. 创建绘图对象并添加图片
////            CreationHelper helper = workbook.getCreationHelper();
////            Drawing<?> drawing = sheet.createDrawingPatriarch();
////            // 创建锚点 (指定图片位置)
////            //定位 C4 单元格 2 3 跨2列1行
////            workbook.setActiveSheet(0); // 激活第一个工作表
////            ClientAnchor anchor = ExcelImageUtils.createImageAnchor(helper,1,2,1,1);
////            // 添加图片
////            drawing.createPicture(anchor, pictureIdx);
//
////            ExcelImageUtils.imgDisplacement(workbook,sheet,"D:/00d9a7a1-bb7a-43dd-b37c-e0d3bad0b746.jpg",1,2,1,1);
//
//            // 3. 设置响应头
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//            response.setHeader("Content-Disposition", "attachment; filename=report.xlsx");
//
//            // 4. 写入响应流
//            workbook.write(response.getOutputStream());
//            workbook.close();
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//    }
//
//    @Override
//    public void importData(MultipartFile file) {
//        TemplateImportRecord record = new TemplateImportRecord();
//        record.setFileName(file.getOriginalFilename());
//        record.setImportTime(new Date());
//
//        try {
//            readExcel(file);
//            List<ExcelData> dataList = parseExcel(file);
//            List<String> errors = validateData(dataList);
//
//            if (!errors.isEmpty()) {
//                record.setStatus("FAIL");
//                record.setErrorMessage(String.join(", ", errors));
//                templateMapper.insertImportRecord(record);
//                return;
//            }
//
//            // 保存数据及图片
//            record.setStatus("SUCCESS");
//            templateMapper.insertImportRecord(record);
//
//            for (ExcelData data : dataList) {
//                String imagePath = saveImage(data.getImage());
//                TemplateData templateData = new TemplateData();
//                templateData.setRecordId(record.getId());
//                templateData.setField1(data.getField1());
//                templateData.setField2(data.getField2());
//                templateData.setImagePath(imagePath);
//                templateMapper.insertTemplateData(templateData);
//            }
//        } catch (Exception e) {
//            record.setStatus("FAIL");
//            record.setErrorMessage(e.getMessage());
//            templateMapper.insertImportRecord(record);
//        }
//    }
//
//    /**
//     * 遍历表格数据
//     * @param file
//     * @throws IOException
//     */
//    public void readExcel(MultipartFile file) throws IOException {
//        // 检查文件是否为空
//        if (file.isEmpty()) {
//            throw new IllegalArgumentException("文件不能为空");
//        }
//
//        try (InputStream is = file.getInputStream();
//             Workbook workbook = WorkbookFactory.create(is)) { // 自动识别格式
//
//            // 遍历所有Sheet
//            for (Sheet sheet : workbook) {
//                System.out.println("Sheet名称: " + sheet.getSheetName());
//
//                // 遍历行
//                for (Row row : sheet) {
//                    // 遍历单元格
//                    for (Cell cell : row) {
//                        // 获取单元格值（自动识别类型）
//                        String cellValue = getCellValueAsString(cell);
//                        System.out.print(cellValue + "\t");
//                    }
//                    System.out.println(); // 换行
//                }
//            }
//        }
//    }
//
//    // 安全获取单元格值的工具方法
//    private String getCellValueAsString(Cell cell) {
//        if (cell == null) {return "";}
//
//        return switch (cell.getCellType()) {
//            case STRING -> cell.getStringCellValue();
//            case NUMERIC ->
//                    DateUtil.isCellDateFormatted(cell) ?
//                            cell.getLocalDateTimeCellValue().toString() :
//                            String.valueOf(cell.getNumericCellValue());
//            case BOOLEAN -> String.valueOf(cell.getBooleanCellValue());
//            case FORMULA -> cell.getCellFormula();
//            case BLANK, _NONE -> "";
//            default -> "[未知类型]";
//        };
//    }
//
//    @Override
//    public List<Sheet1Data> querySheet1Data() {
//        Sheet1Data sheet1Data=new Sheet1Data();
//        sheet1Data.setField1_1("1");
//        sheet1Data.setField1_2("1-1");
//        sheet1Data.setImagePath2("img01");
//        return Arrays.asList(sheet1Data);
//    }
//
//    @Override
//    public List<Sheet2Data> querySheet2Data() {
//        Sheet2Data sheet2Data=new Sheet2Data();
//        sheet2Data.setField2_1("2-1");
//        sheet2Data.setField2_2("2-2");
//        sheet2Data.setImagePath2("img02");
//        return Arrays.asList(sheet2Data);
//    }
//
//    // 使用 Apache POI 解析 Excel 的伪代码 （弃用）
//    @Deprecated
//    public List<ExcelData> parseExcel(MultipartFile file) throws IOException {
//        List<ExcelData> dataList = new ArrayList<>();
//        Workbook workbook = WorkbookFactory.create((POIFSFileSystem) file);
//        Sheet sheet = workbook.getSheetAt(0);
//        for (Row row : sheet) {
//            ExcelData data = new ExcelData();
//            data.setColumn1(row.getCell(0).getStringCellValue());
//            data.setColumn2((int) row.getCell(1).getNumericCellValue());
//            dataList.add(data);
//        }
//        workbook.close();
//        return dataList;
//    }
//
//    private List<String> validateData(List<ExcelData> dataList) {
//        List<String> errors = new ArrayList<>();
//        for (ExcelData data : dataList) {
//            if (data.getField1().length() > 100) {
//                errors.add("字段1长度超过限制");
//            }
//            // 图片校验
//            if (data.getImage() != null) {
//                if (data.getImage().length > 2 * 1024 * 1024) {
//                    errors.add("图片大小超过2MB");
//                }
//                try {
//                    BufferedImage image = ImageIO.read(new ByteArrayInputStream(data.getImage()));
//                    if (image.getWidth() > 1024 || image.getHeight() > 1024) {
//                        errors.add("图片尺寸超过1024x1024");
//                    }
//                } catch (IOException e) {
//                    errors.add("图片格式错误");
//                }
//            }
//        }
//        return errors;
//    }
//
//    private String saveImage(byte[] imageData) throws IOException {
//        String fileName = UUID.randomUUID() + ".png";
//        Path path = Paths.get(uploadDir, fileName);
//        Files.write(path, imageData);
//        return fileName;
//    }
//
//
//    @Override
//    public void asyncGenerateTemplate(DeferredResult<ResponseEntity<Resource>> deferredResult) {
//        try (XSSFWorkbook workbook = new XSSFWorkbook()) {
//            XSSFSheet sheet = workbook.createSheet("Sheet1");
//            // 填充数据库数据到Excel
////            List<TemplateData> dataList = dataMapper.selectAll();
//            // 填充逻辑...
//
//            // 添加图片（示例）
//            byte[] imageBytes = Files.readAllBytes(Paths.get("static/images/demo.png"));
//            int imageIndex = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG);
//            CreationHelper helper = workbook.getCreationHelper();
//            Drawing<?> drawing = sheet.createDrawingPatriarch();
//            ClientAnchor anchor = helper.createClientAnchor();
//            anchor.setCol1(1);
//            anchor.setRow1(1);
//            Picture pict = drawing.createPicture(anchor, imageIndex);
//
//            ByteArrayOutputStream bos = new ByteArrayOutputStream();
//            workbook.write(bos);
//            InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(bos.toByteArray()));
//
//            deferredResult.setResult(ResponseEntity.ok()
//                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=template.xlsx")
//                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
//                    .body(resource));
//        } catch (Exception e) {
//            deferredResult.setErrorResult(ResponseEntity.internalServerError().body(e.getMessage()));
//        }
//    }
//}
//
//
//
//
